import json
import os

import requests
from openai import OpenAI


def verify_education(arguments):
    """
    1:验证学历的工具(梦远数据的API)
    """
    try:

        api_key = os.getenv("MY_XXW_BGCX_API_KEY")
        # 设置url
        url = 'https://www.apimy.cn/api/xxw/bgcx?key=' + api_key
        vcode = arguments["vcode"]

        # 发送post请求
        response = requests.post(url, data={'vcode': vcode})

        # 获取响应内容
        result = response.json()

        # 打印结果
        print(result)
        print(type(result))
        if result["code"] == 200:
            return json.dumps(result["data"], ensure_ascii=False)
        else:
            return f"学历验证失败:{result['msg']}"
    except Exception as e:
        print(f"学历验证失败:{e}")
        return "学历验证失败"


# 2:创建工具列表
tools = [
    {
        "type": "function",
        "function": {
            "name": "verify_education",
            "description": "通过学信网验证码查询并验证学历信息, 包括:姓名, 学校,专业等详细内容",
            "parameters": {
                "type": "object",
                "properties": {
                    "vcode": {
                        "type": "string",
                        "description": "学信网验证码"
                    }
                },
                "required": ["vcode"]
            }
        }
    }
]

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)


def get_ai_response(messages):
    completion = client.chat.completions.create(
        model="qwen-plus",
        messages=messages,
        tools=tools,
    )

    return completion


def main():
    # user_input = "上午和下午的区别?"
    #user_input = "学历验证:A7FKKV3C4Q40RWGD"
    user_input = "帮我进行学历验证"
    messages = [{"role": "user", "content": user_input}]
    completion = get_ai_response(messages)
    print(completion)

    assistant_output = completion.choices[0].message

    # 如果需要function calling ,则content为空

    # 如果需要function calling,则tool_calls不为空
    tool_calls = completion.choices[0].message.tool_calls

    if assistant_output.content == "":
        assistant_output.content = ""
    messages.append(assistant_output)

    if assistant_output.content == "" and tool_calls is not None:
        # 处理function calling
        print("需要处理function calling...")
        for tool_call in tool_calls:
            tool_call_id = tool_call.id
            func_name = tool_call.function.name
            func_arguments = tool_call.function.arguments
            arguments = json.loads(func_arguments)
            print(f"正在调用工具 [{func_name}]，参数：{arguments}")
            if func_name == "verify_education":
                tool_result = verify_education(arguments)
                print(f"工具返回结果:{tool_result}")

                # 构造工具返回信息
                tool_message = {
                    "role": "tool",
                    "tool_call_id": tool_call_id,
                    "content": tool_result,  # 保持原始工具输出
                }
                messages.append(tool_message)
                print(f"messages:{messages}")
                completion = get_ai_response(messages)
                print(f"第二次调用大模型:{completion}")
                print(f"最终的答案:{completion.choices[0].message.content}")




            else:
                result = "不支持的函数"






    else:
        print(f"不需要二次处理,可以直接返回内容:{assistant_output.content}")


if __name__ == '__main__':
    main()
